package com.util.lzj;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
	
	private Connection conn = null;
	
	private PreparedStatement ps = null;
	
	/**
	 * 获取数据库连接
	 * @return
	 */
	public Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
			return conn;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public PreparedStatement getPreparedStatement(String sql) {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project2","root","root");
			this.ps = conn.prepareStatement(sql);
			return this.ps;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}	
		return null;
	}
	
	public Statement getStatement() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
			
			return conn.createStatement();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void closeAll() {
		try {
			if(ps != null ) {
				this.ps.close();
			}
			if(conn != null) {
				this.conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
